
using System;
using System.Data;
using System.Linq;
using System.Linq.Dynamic;
using System.Linq.Dynamic.Core;
using System.Linq.Expressions;
using System.Threading.Tasks;
using System.Collections.Generic;
using Microsoft.EntityFrameworkCore;

using Abp.UI;
using Abp.AutoMapper;
using Abp.Extensions;
using Abp.Authorization;
using Abp.Domain.Repositories;
using Abp.Application.Services.Dto;
using Abp.Linq.Extensions;


using JYJ.AiYard.StationManagement.TbYardLocalFrees;
using JYJ.AiYard.StationManagement.TbYardLocalFrees.Dtos;
using JYJ.AiYard.StationManagement.TbYardLocalFrees.DomainService;
using JYJ.AiYard.StationManagement.TbYardLocalFrees.Authorization;
using JYJ.AiYard.StationManagement.YardReport;
using JYJ.AiYard.StationManagement.YardCommonHald;

namespace JYJ.AiYard.StationManagement.TbYardLocalFrees
{
    /// <summary>
    /// TbYardLocalFree应用层服务的接口实现方法  
    ///</summary>
    [AbpAuthorize]
    public class TbYardLocalFreeAppService : AiYardAppServiceBase, ITbYardLocalFreeAppService
    {
        private readonly IRepository<TbYardLocalFree, long> _entityRepository;

        private readonly ITbYardLocalFreeManager _entityManager;

        /// <summary>
        /// 构造函数 
        ///</summary>
        public TbYardLocalFreeAppService(
        IRepository<TbYardLocalFree, long> entityRepository
        ,ITbYardLocalFreeManager entityManager
        )
        {
            _entityRepository = entityRepository; 
             _entityManager=entityManager;
        }


        /// <summary>
        /// 获取TbYardLocalFree的分页列表信息
        ///</summary>
        /// <param name="input"></param>
        /// <returns></returns>
		[AbpAuthorize(TbYardLocalFreePermissions.Query)] 
        public async Task<PagedResultDto<TbYardLocalFreeListDto>> GetPaged(GetTbYardLocalFreesInput input)
		{
			List<long> StationList = new List<long>();
			tbQFilterText filterText = input.FilterText.ToObject<tbQFilterText>();
			if (filterText.StationId == null || filterText.StationId <= 0)
			{
				StationList = GetCurrenUserOrganizationAndChildrenUnit();
			}
			else
			{
				StationList.Add((long)filterText.StationId);
			}
			var query = _entityRepository.GetAll().Where(o => StationList.Contains(o.Station_ID));
            // TODO:根据传入的参数添加过滤条件
            if (!string.IsNullOrEmpty(filterText.FilterText))
            {
                query = query.Where(o => o.LocalFreeName.Contains(filterText.FilterText));

            }

			var count = await query.CountAsync();

			var entityList = await query
                    .OrderBy(input.Sorting).AsNoTracking()
					.PageBy(input)
					.ToListAsync(); 
			var entityListDtos =entityList.MapTo<List<TbYardLocalFreeListDto>>();

			return new PagedResultDto<TbYardLocalFreeListDto>(count,entityListDtos);
		}


		/// <summary>
		/// 通过指定id获取TbYardLocalFreeListDto信息
		/// </summary>
		[AbpAuthorize(TbYardLocalFreePermissions.Query)] 
		public async Task<TbYardLocalFreeListDto> GetById(EntityDto<long> input)
		{
			var entity = await _entityRepository.GetAsync(input.Id);

		    return entity.MapTo<TbYardLocalFreeListDto>();
		}

		/// <summary>
		/// 获取编辑 TbYardLocalFree
		/// </summary>
		/// <param name="input"></param>
		/// <returns></returns>
		[AbpAuthorize(TbYardLocalFreePermissions.Create,TbYardLocalFreePermissions.Edit)]
		public async Task<GetTbYardLocalFreeForEditOutput> GetForEdit(NullableIdDto<long> input)
		{
			var output = new GetTbYardLocalFreeForEditOutput();
            TbYardLocalFreeEditDto editDto;

			if (input.Id.HasValue)
			{
				var entity = await _entityRepository.GetAsync(input.Id.Value);

				editDto = entity.MapTo<TbYardLocalFreeEditDto>(); 
			}
			else
			{
				editDto = new TbYardLocalFreeEditDto();
			}

			output.TbYardLocalFree = editDto;
			return output;
		}


		/// <summary>
		/// 添加或者修改TbYardLocalFree的公共方法
		/// </summary>
		/// <param name="input"></param>
		/// <returns></returns>
		[AbpAuthorize(TbYardLocalFreePermissions.Create,TbYardLocalFreePermissions.Edit)]
		public async Task<Dictionary<string,string>> CreateOrUpdate(CreateOrUpdateTbYardLocalFreeInput input)
		{
			Dictionary<string, string> result = new Dictionary<string, string>();
            if (input.TbYardLocalFree.Station_ID <= 0)
            {
				result.Add("retype", "-1");
				result.Add("revalue", "请选择确定的场所名称!");
				return result; 
            }

            if (input.TbYardLocalFree.Id.HasValue)
			{
				if (_entityRepository.GetAll().Where(o => o.Station_ID == input.TbYardLocalFree.Station_ID
			   && o.LocalFreeName == input.TbYardLocalFree.LocalFreeName && o.Id != input.TbYardLocalFree.Id).Count() > 0)
				{
					result.Add("retype", "-1");
					result.Add("revalue", "免单类型名称不允许重复!");
					return result; 
				}
				await Update(input.TbYardLocalFree);
			}
			else
			{
				if (_entityRepository.GetAll().Where(o => o.Station_ID == input.TbYardLocalFree.Station_ID && o.LocalFreeName == input.TbYardLocalFree.LocalFreeName).Count() > 0)
				{
					result.Add("retype", "-1");
					result.Add("revalue", "免单类型名称不允许重复!");
					return result;  
				}
				await Create(input.TbYardLocalFree);
			}
			result.Add("retype", "1");
			result.Add("revalue", "保存成功!");
			return result;
		}


		/// <summary>
		/// 新增TbYardLocalFree
		/// </summary>
		[AbpAuthorize(TbYardLocalFreePermissions.Create)]
		protected virtual async Task<TbYardLocalFreeEditDto> Create(TbYardLocalFreeEditDto input)
		{
            //TODO:新增前的逻辑判断，是否允许新增 
            var entity=input.MapTo<TbYardLocalFree>();

            
             
            entity = await _entityRepository.InsertAsync(entity);
			return entity.MapTo<TbYardLocalFreeEditDto>();
		}

		/// <summary>
		/// 编辑TbYardLocalFree
		/// </summary>
		[AbpAuthorize(TbYardLocalFreePermissions.Edit)]
		protected virtual async Task Update(TbYardLocalFreeEditDto input)
		{
            //TODO:更新前的逻辑判断，是否允许更新
            
            var entity = await _entityRepository.GetAsync(input.Id.Value);
			input.MapTo(entity); 
		    await _entityRepository.UpdateAsync(entity);
		}



		/// <summary>
		/// 删除TbYardLocalFree信息的方法
		/// </summary>
		/// <param name="input"></param>
		/// <returns></returns>
		[AbpAuthorize(TbYardLocalFreePermissions.Delete)]
		public async Task Delete(EntityDto<long> input)
		{
			//TODO:删除前的逻辑判断，是否允许删除
			await _entityRepository.DeleteAsync(input.Id);
		}



		/// <summary>
		/// 批量删除TbYardLocalFree的方法
		/// </summary>
		[AbpAuthorize(TbYardLocalFreePermissions.BatchDelete)]
		public async Task BatchDelete(List<long> input)
		{
			// TODO:批量删除前的逻辑判断，是否允许删除
			await _entityRepository.DeleteAsync(s => input.Contains(s.Id));
		}


		///// <summary>
		///// 导出TbYardLocalFree为excel表,等待开发。
		///// </summary>
		///// <returns></returns>
		//public async Task<FileDto> GetToExcel()
		//{
		//	var users = await UserManager.Users.ToListAsync();
		//	var userListDtos = ObjectMapper.Map<List<UserListDto>>(users);
		//	await FillRoleNames(userListDtos);
		//	return _userListExcelExporter.ExportToFile(userListDtos);
		//}

    }
}


